/*
 * Unidata Platform Community Edition
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 * This file is part of the Unidata Platform Community Edition software.
 *
 * Unidata Platform Community Edition is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Unidata Platform Community Edition is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package org.unidata.mdm.meta.service.impl.data.instance;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.unidata.mdm.core.type.model.AttributeElement;
import org.unidata.mdm.core.type.model.IndexedElement;
import org.unidata.mdm.core.type.model.LookupElement;
import org.unidata.mdm.core.type.model.ModelSearchEntry;
import org.unidata.mdm.core.type.model.ReferencePresentationElement;
import org.unidata.mdm.core.type.model.RegisterElement;
import org.unidata.mdm.core.type.model.RelationElement;
import org.unidata.mdm.core.type.model.SearchableElement;
import org.unidata.mdm.core.type.model.ValidityPeriodElement;
import org.unidata.mdm.meta.service.LookupReferenceSupport;
import org.unidata.mdm.meta.service.impl.instance.ReferencePresentationImpl;
import org.unidata.mdm.meta.type.instance.DataModelInstance;
import org.unidata.mdm.meta.type.model.entities.RelType;
import org.unidata.mdm.meta.type.model.entities.Relation;
import org.unidata.mdm.search.type.IndexField;
import org.unidata.mdm.system.type.support.IdentityHashSet;

/**
 * @author Mikhail Mikhailov
 *         Relation wrapper.
 */
public class RelationImpl extends AbstractEntityImpl<Relation>
    implements IndexedElement, SearchableElement, RelationElement, LookupReferenceSupport {
    /**
     * The relation entry type.
     */
    private static final String ENTRY_TYPE_RELATION = "RELATION";
    /**
     * The index fields.
     */
    private final Map<String, IndexField> indexFields;
    /**
     * The left (from) side.
     */
    private final RegisterElement left;
    /**
     * Left side presentation info.
     */
    private final ReferencePresentationElement leftPresentation;
    /**
     * The right (to) side.
     */
    private final RegisterElement right;
    /**
     * Right side presentation info.
     */
    private final ReferencePresentationElement rightPresentation;
    /**
     * Lookups, refernced by this register.
     */
    private final Map<LookupElement, Set<AttributeElement>> referencedLookups = new IdentityHashMap<>();
    /**
     * Constructor.
     */
    public RelationImpl(Relation r, DataModelInstance i) {
        super(r, Collections.emptyList());
        this.left = i.getRegister(r.getFromEntity());
        this.right = i.getRegister(r.getToEntity());

        Objects.requireNonNull(this.left, "Left (FROM) entity must not be null.");
        Objects.requireNonNull(this.right, "Right (TO) entity must not be null.");

        ((RegisterImpl) this.left).putOutgoingRelation(this, this.right);
        ((RegisterImpl) this.right).putIncommingRelation(this, this.left);

        // Left is just reserved.
        this.leftPresentation = new ReferencePresentationImpl(Collections.emptyList(), Collections.emptyList(), false);
        this.rightPresentation = new ReferencePresentationImpl(r.getToEntityDefaultDisplayAttributes(),
                r.getToEntitySearchAttributes(),
                r.isUseAttributeNameForDisplay());

        for (AttributeElement ae : getAttributes().values()) {

            if (ae.isLookupLink()) {
                LookupElement le = i.getLookup(ae.getLookupLink().getLookupLinkName());
                Objects.requireNonNull(le, "Lookup link attribute cannot reference a null object.");
                fixLookupLinkType(le, ae);
                referencedLookups.computeIfAbsent(le, k -> new IdentityHashSet<AttributeElement>()).add(ae);
                ((LookupImpl) le).putReferencingRelations(this, referencedLookups.get(le));
            }
        }

        this.indexFields = MapUtils.isEmpty(getAttributes())
                ? Collections.emptyMap()
                : getAttributes().entrySet().stream()
                    .filter(e -> e.getValue().isIndexed())
                    .map(e -> Pair.of(e.getKey(), e.getValue().getIndexed()))
                    .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public String getId() {
        return getName();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRelation() {
        return true;
    }
    /**
     * @return the relation
     */
    @Override
    public RelationElement getRelation() {
        return this;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isValidityPeriod() {
        return true;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public ValidityPeriodElement getValidityPeriod() {
        return this;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isIndexed() {
        return true;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRequired() {
        return getSource().isRequired();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isReference() {
        return getSource().getRelType() == RelType.REFERENCES;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isContainment() {
        return getSource().getRelType() == RelType.CONTAINS;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isManyToMany() {
        return getSource().getRelType() == RelType.MANY_TO_MANY;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public IndexedElement getIndexed() {
        return this;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, IndexField> getIndexFields() {
        return indexFields;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public RegisterElement getLeft() {
        return left;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public ReferencePresentationElement getLeftPresentation() {
        return leftPresentation;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public RegisterElement getRight() {
        return right;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public ReferencePresentationElement getRightPresentation() {
        return rightPresentation;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public Map<LookupElement, Set<AttributeElement>> getReferencedLookups() {
        return referencedLookups;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSearchable() {
        return true;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public SearchableElement getSearchable() {
        return this;
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<ModelSearchEntry> getModelSearchEntries() {

        List<ModelSearchEntry> entries = new ArrayList<>();

        entries.add(new ModelSearchEntry(ENTRY_TYPE_RELATION, getName(), ENTRY_TYPE_RELATION, getName())
                .withEntryDisplayName(getDisplayName())
                .withEntryDescription(getDescription()));

        entries.addAll(getAttributeEntries(ENTRY_TYPE_RELATION, getName()));

        return entries;
    }
}
